package com.itheima.security;

import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: bowen
 * @Date: 2019/7/1 17:16
 * @Description:
 */
public class UserService implements UserDetailsService {

	@Autowired
	BCryptPasswordEncoder passwordEncoder;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//用Map来模拟数据库，存入用户信息
		Map<String, User> map = new HashMap<>();
		User user = new User();
		user.setUsername("admin");
		user.setPassword(passwordEncoder.encode("admin"));

		User user1 = new User();
		user1.setUsername("xiaoming");
		user1.setPassword(passwordEncoder.encode("xiaoming"));
		map.put(user.getUsername(),user);
		map.put(user1.getUsername(),user1);

		User u = map.get(username);
		if(u==null){
        //  数据库不存在这个用户
			return null;
		}

		List<GrantedAuthority> list = new ArrayList();
		if(u.getUsername().equals("admin")) {
			list.add(new SimpleGrantedAuthority("add"));
		}
		list.add(new SimpleGrantedAuthority("delete"));
		list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

		return new org.springframework.security.core.userdetails.User(username,
				u.getPassword(),
				list);
	}


	//public static void main(String[] args) {
	//	System.out.println(new BCryptPasswordEncoder().encode("1234"));
	//}
}
